import { EMClient } from "../index";
import { ElMessage } from "element-plus";
import { useImStore } from "@/stores/modules/im";
export const imConnectListener = () => {
  const imStore = useImStore();
  let reTime = 0;
  const mountConnectEventListener = () => {
    EMClient.addEventHandler("connection", {
      onConnected: () => {
        console.log("链接成功");
        imStore.$patch({
          onLine: true,
          userId: EMClient.user
        });
        imStore.getFetchUserInfoById();
        imStore.getContacts();
      },
      onDisconnected: () => {
        console.log("链接失败");
        reTime++;
        imStore.$patch({
          onLine: false
        });
        if (reTime < 4) {
          imStore.doLogin();
          ElMessage.error("尝试进行第" + reTime + "次重连...");
        } else {
          ElMessage.error("您已经离线，请重新登录");
        }
      },
      onOnline: () => {
        console.log("上线成功");
        imStore.$patch({
          onLine: true
        });
      }, // 本机网络连接成功。
      onOffline: () => {
        console.log("已掉线");
        ElMessage.error("您已经离线，请重新登录");
        imStore.$patch({
          onLine: false
        });
        imStore.doLogin();
      }, // 本机网络掉线。
      onError: error => {
        console.log("发生错误", error);
      }
    });
  };

  return {
    mountConnectEventListener
  };
};
